package hub

import (
	"encoding/binary"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/grand"
	"paco_toolkit/NIC510"
)

func StartHub() {
	g.Log().Line(true).Debug("Start Hub")
	//ConnetHub()
	client := CreateMqttClient("cid_Hub_HZ_"+grand.Digits(10), onConnet, onConnetLost)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		g.Log().Line(true).Error(token.Error())
	}
}

func onConnet(client mqtt.Client) {
	g.Log().Line(true).Debug("onConnet")
	debug_mode := g.Cfg().GetBool("basic.debug")
	if debug_mode {
		//本地测试
		SubscribeNIC510(client)
	} else {
		//生产环境
		SubscribeNIC510(client)
	}
}
func onConnetLost(client mqtt.Client, err error) {
	g.Log().Line(true).Debug("onConnetLost")
}

func SubscribeNIC510(client mqtt.Client) {
	topic_p := "P/NIC510/#"
	debug_mode := g.Cfg().GetBool("basic.debug")
	if debug_mode {
		topic_p = "P/NIC510/#"
	} else {
		topic_p = "P/NIC510/#"
	}
	// 订阅主题
	if token := client.Subscribe(topic_p, 0, func(c mqtt.Client, msg mqtt.Message) {
		topic := msg.Topic()
		topic_arr := gstr.Split(topic, "/")
		addr := topic_arr[2]
		//g.Log().Line(true).Debug("NIC510 recv from topic:" + msg.Topic())
		//g.Log().Line(true).Debug("NIC510 recv from addr:" + addr)
		//g.Log().Line(true).Debugf("NIC510 recv msg len: %d", len(msg.Payload()))
		DecodeNIC510Pack(msg.Payload(), addr)

	}); token.Wait() && token.Error() != nil {
		g.Log().Line(true).Error(token.Error().Error())
	}
}

func DecodeNIC510Pack(data []byte, addr string) {
	if pack, err := NIC510.DecodePack(data); err != nil {
		g.Log().Line(true).Error(err.Error())
	} else {
		var c = pack.C
		if c == 0x82 {
			//f_status := NIC510.DecodeStatus(pack.Data)
			//g.Log().Line(true).Debug(f_status)
			//g.Log().Line(true).Debug("NIC510.DecodeStatus ok")
		} else if c == 0x83 {

		}
	}
}

func ReadNIC510State() {
	clients_data, _ := GetApiClients(gdb.Map{
		"_page":          1,
		"_limit":         100000,
		"_like_clientid": "cid_NIC510_",
	})
	c := CreateMqttClient("cid_ReadNIC510State_"+grand.Digits(10), nil, nil)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		//panic(token.Error())
		g.Log().Line(true).Debug(token.Error().Error())
	}
	for _, item := range clients_data {
		cid := gconv.String(item["clientid"])
		cid_arr := gstr.Split(cid, "_")
		addr := cid_arr[2]
		topic_s := "S/NIC510/" + addr
		g.Log().Line(true).Debug(topic_s)
		var data []byte
		var status NIC510.State
		size := uint16(binary.Size(status))
		msg := NIC510.CreateMsg(02, 0, size, data)
		g.Log().Line(true).Debugf("NIC510 send msg: % X", msg)
		// 发布消息
		token := c.Publish(topic_s, 0, false, msg)
		token.Wait()
	}
	c.Disconnect(250)
}
